Imports System.Windows.Forms

Public Class frmUpgradeWiz

    Dim WithEvents PDoxProject As clsProject

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Project.DB.Cancel()
        MainForm.ProgressComplete()
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub frmUpgradeWiz_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'look in windows directory for .prj files referenced in WRDB.ini (will later probably move to program directory)
        'there is no constant to get the WINDOWS directory name, only System32--strip off manually

        Dim prjDir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
        prjDir = prjDir.Substring(0, prjDir.LastIndexOf("\"))

        If Not My.Computer.FileSystem.FileExists(prjDir & "\WRDB.INI") Then
            WarningMsg("It appears that WRDB 4.5 is not installed on this computer, so this function is disabled.")
            Close()
            Exit Sub
        End If

        If Project Is Nothing Then
            optParadox.Checked = True
            optMerge.Enabled = False
        End If

        Dim iniFile As New IniFile.clsIniFile(prjDir & "\WRDB.INI", False)
        With iniFile
            Me.lvwProjects.Items.Clear()
            Dim NumProjects As Int16 = Val(.GetKeyText("WRDB", "NumProjects"))
            Dim LastProject As Int16 = Val(.GetKeyText("WRDB", "LastProject"))
            For i As Int16 = 1 To NumProjects
                Dim Name As String = .GetKeyText("WRDB", "ProjectName" & i)
                Dim Desc As String = .GetKeyText("WRDB", "ProjectDesc" & i)
                Dim lvitem As New ListViewItem(Name)
                lvitem.SubItems.Add(Desc)
                Me.lvwProjects.Items.Add(lvitem)
                If i = LastProject Then lvitem.Selected = True
            Next
        End With
        Me.lvwProjects.Focus()
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        With TabControl1
            Me.btnPrevious.Enabled = .SelectedIndex <> 0
            If .SelectedIndex = .TabCount - 1 Then
                Me.btnNext.Text = "&Upgrade"
            Else
                Me.btnNext.Text = "&Next >"
            End If
        End With
    End Sub

    Private Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
        With TabControl1
            If .SelectedIndex = .TabCount - 1 Then
                UpgradeProjects()
            Else
                .SelectedIndex += 1
            End If
        End With
    End Sub

    Private Sub btnPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
        TabControl1.SelectedIndex -= 1
    End Sub

    Private Sub UpgradeProjects()
        Try
            Me.lstProgress.Items.Clear()
            btnNext.Enabled = False
            btnPrevious.Enabled = False
            Dim prjDir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
            prjDir = prjDir.Substring(0, prjDir.LastIndexOf("\"))

            'get list of current WRDB 5.0 projects so can warn if is going to be replaced
            Dim WRDB5Projects As New Generic.List(Of String)
            For Each Section As String In clsConnections.GetProjectList.Keys
                WRDB5Projects.Add(Section)
            Next

            Dim wrdbFile As New IniFile.clsIniFile(prjDir & "\WRDB.INI", False)
            With wrdbFile
                Dim NumProjects As Int16 = Val(.GetKeyText("WRDB", "NumProjects"))
                Dim LastProject As Int16 = Val(.GetKeyText("WRDB", "LastProject"))

                For Each lvItem As ListViewItem In lvwProjects.SelectedItems
                    For i As Int16 = 1 To NumProjects
                        Dim Name As String = .GetKeyText("WRDB", "ProjectName" & i)
                        Dim Desc As String = .GetKeyText("WRDB", "ProjectDesc" & i)
                        Dim prjFile As New IniFile.clsIniFile(prjDir & "\" & Name & ".prj", False)
                        If lvItem.Text = Name Then
                            Dim NewName As String = Strings.Left(Name, 30)
                            Do
                                If WRDB5Projects.Contains(NewName) Then
                                    Select Case MessageBox.Show(StringFormat("Warning: you already have an existing WRDB project with this name ({0}); do you want to overwrite this project with the project you are importing from WRDB 4.5?\n\n(If you select 'Yes', the project specification will be overwritten but existing data files will not be replaced; if you select 'No', you will be prompted to enter a new project name.)", NewName), "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)
                                        Case Windows.Forms.DialogResult.Yes : Exit Do
                                        Case Windows.Forms.DialogResult.No : NewName = InputBox("Enter new name for project being imported:", "Upgrade Wizard", NewName) : If NewName = "" Then Exit Sub
                                        Case Windows.Forms.DialogResult.Cancel : Exit Sub
                                    End Select
                                Else
                                    Exit Do
                                End If
                            Loop
                            If Not MainWRDB.DataProviderAvailable(clsDB.enumDBType.Paradox) Then Exit Sub
                            Try
                                PDoxProject = New clsProject(NewName)
                            Catch ex As Exception
                                WarningMsg(ex.Message)
                                Exit Sub
                            End Try
                            With PDoxProject
                                .Description = Desc
                                .TitlebarText = prjFile.GetKeyText("Settings", "TitleBarText")
                                .DesktopGraphicFile = prjFile.GetKeyText("Settings", "DesktopGraphic")
                                If .DesktopGraphicFile.EndsWith(".pcx", StringComparison.OrdinalIgnoreCase) Then
                                    lstProgress.Items.Add("The legacy project referenced a PCX desktop graphic file; this format is no longer supported.")
                                    .DesktopGraphicFile = ""
                                End If
                                .MasterTableName = prjFile.GetKeyText("Settings", "MasterDB").ToUpper.Replace(".DB", "")
                                Try
                                    .DB = clsDB.GetDataProvider(clsDB.enumDBType.Paradox)
                                Catch ex As Exception
                                    WarningMsg("Unable to find data provider libraries.", , ex)
                                    Exit Sub
                                End Try
                                '.DB.Project = PDoxProject
                                .WorkingDir = prjFile.GetKeyText("Settings", "TempPath")
                                .DB.DataSource = .WorkingDir
                                .MasterDir = prjFile.GetKeyText("Settings", "MasterPath")
                                .SupportDir = prjFile.GetKeyText("Settings", "SupportPath")
                                .SupportDirProject = prjFile.GetKeyText("Settings", "ProjectSupportPath")
                                .ReportHeading1 = prjFile.GetKeyText("Settings", "Heading1")
                                .ReportHeading2 = prjFile.GetKeyText("Settings", "Heading2")
                                .DB.DatabaseType = clsDB.enumDBType.Paradox
                                .DB.CreateConnection()
                                AddHandler .Progress, AddressOf MainForm.Project_Progress
                            End With

                            If Me.optParadox.Checked Then
                                PDoxProject.SavePreferences()
                                Me.lstProgress.Items.Add("Legacy WRDB project was successfully added: " & Name)
                            Else
                                Dim NewProject As clsProject = Project.Clone

                                With NewProject
                                    .Name = NewName
                                    .Description = PDoxProject.Description
                                    .TitlebarText = PDoxProject.TitlebarText
                                    .DesktopGraphicFile = PDoxProject.DesktopGraphicFile
                                    .MasterTableName = PDoxProject.MasterTableName.Replace(".DB", "").Replace(".db", "")
                                    .SavePreferences()
                                End With

                                Me.lstProgress.Items.Add("Upgrading legacy WRDB project: " & Name)

                                'import all other support and data tables

                                SetProject(NewName)

                                With Project
                                    For Each s As String In PDoxProject.GetTableListAll()
                                        If s.ToUpper <> "TRACKING" Then
                                            Dim DestTable As String = Proper(s)
                                            Dim Update As Boolean = True
                                            Select Case .GetTableType(s)
                                                Case clsProject.enumTableTypes.Working, clsProject.enumTableTypes.Master : Update = False
                                            End Select
                                            Try
                                                If .CopyTable(DestTable, s, PDoxProject, Update, False, True) Then
                                                    Me.lstProgress.Items.Add(String.Format("  Successfully imported Paradox table {0} into {1}", s, DestTable))
                                                Else
                                                    Me.lstProgress.Items.Add("  Unable to import Paradox table " & s)
                                                End If
                                            Catch ex As Exception
                                                Me.lstProgress.Items.Add("  Source table is CORRUPTED: " & s)
                                            End Try
                                            If Project.DB.Cancelled Then
                                                Me.lstProgress.Items.Add("***Upgrade process was cancelled by user***")
                                                Exit Sub
                                            End If
                                        End If
                                        Me.lstProgress.SelectedIndex = lstProgress.Items.Count - 1
                                        Me.lstProgress.SelectedIndex = -1
                                        If ProgressCancel Then Exit For
                                    Next

                                    'delete all tracking entries from above operations so don't get duplicates

                                    .DB.ExecuteNonQuery($"DELETE FROM {Project.FullTableName(clsProject.enumTableTypes.Tracking)}")

                                    'import Tracking table

                                    If .CopyTable("Tracking", "Tracking", PDoxProject, True) Then
                                        Me.lstProgress.Items.Add("  Successfully imported and updated Tracking table")
                                    Else
                                        Me.lstProgress.Items.Add("  Unable to import Tracking table")
                                    End If
                                    .SavePreferences()
                                End With
                            End If
                            'try to fix up the table 

                            MainForm.WriteProgress("Synchronizing Tracking table")
                            Try
                                Project.SynchTrackingRecords()
                            Catch ex As Exception
                                WarningMsg(ex.Message)
                            End Try

                            MainForm.ProgressComplete()
                            'Exit For
                        End If
                    Next
                Next
            End With
            lstProgress.Items.Add("***All Projects have been upgraded***")
            MainForm.ProgressComplete()
            Me.btnNext.Enabled = False
            Me.btnCancel.Text = "Close"
            Me.AcceptButton = btnCancel
            WarningMsg("All project tables have been imported. Please note that this version of WRDB uses additional fields and validation Suppport tables (e.g., Station Types) that need to be properly filled. You can do this manually by opening the Support table browser and reviewing the tables. The 'Check...' button on that form can also be used to automatically create missing validation records.")
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub lvwProjects_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwProjects.DoubleClick
        Me.btnNext.PerformClick()
    End Sub

    Private Sub opt_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optParadox.DoubleClick, optMerge.DoubleClick
        Me.btnNext.PerformClick()
    End Sub

    Private Sub Project_Progress(ByRef DB As clsDB, ByVal Value As Integer, ByVal MaxValue As Integer, ByVal ProgressText As String) Handles PDoxProject.Progress
        If Not MainForm.WriteProgress(Value, MaxValue, ProgressText, ProgressBarStyle.Blocks, True) Then DB.Cancel()
    End Sub

    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        ShowHelp(Me, "14")
    End Sub
End Class
